/****************************************************************************
 Copyright (c) 2010-2012 cocos2d-x.org
 Copyright (c) 2012 greathqy
 
 http://www.cocos2d-x.org
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

#include "HttpClient.h"
// #include "platform/CCThread.h"

#include "curl/curl.h"
#define MAX_Thread 16

#ifndef usleep
#include "libwebsockets.h"
#endif

NS_CC_EXT_BEGIN

static CCHttpClient *s_pHttpClient[MAX_Thread] = {0};


typedef size_t (*write_callback)(void *ptr, size_t size, size_t nmemb, void *stream);

// Callback function used by libcurl for collect response data
static size_t writeData(void *ptr, size_t size, size_t nmemb, void *stream)
{
    std::vector<char> *recvBuffer = (std::vector<char>*)stream;
    size_t sizes = size * nmemb;
    
    // add data to the end of recvBuffer
    // write data maybe called more than once in a single request
    recvBuffer->insert(recvBuffer->end(), (char*)ptr, (char*)ptr+sizes);
    
    return sizes;
}

// Callback function used by libcurl for collect header data
static size_t writeHeaderData(void *ptr, size_t size, size_t nmemb, void *stream)
{
    std::vector<char> *recvBuffer = (std::vector<char>*)stream;
    size_t sizes = size * nmemb;
    
    // add data to the end of recvBuffer
    // write data maybe called more than once in a single request
    recvBuffer->insert(recvBuffer->end(), (char*)ptr, (char*)ptr+sizes);
    
    return sizes;
}


static int processGetTask(CCHttpRequest *request, write_callback callback, void *stream, long *errorCode, write_callback headerCallback, void *headerStream);
static int processPostTask(CCHttpRequest *request, write_callback callback, void *stream, long *errorCode, write_callback headerCallback, void *headerStream);
static int processPutTask(CCHttpRequest *request, write_callback callback, void *stream, long *errorCode, write_callback headerCallback, void *headerStream);
static int processDeleteTask(CCHttpRequest *request, write_callback callback, void *stream, long *errorCode, write_callback headerCallback, void *headerStream);
// int processDownloadTask(HttpRequest *task, write_callback callback, void *stream, int32_t *errorCode);


// Worker thread
static void* networkThread(void* data)
{    
    CCHttpClient* httpClient = (CCHttpClient*)data;
    
    CCHttpRequest *request = NULL;
    
    while (true) 
    {
        if (httpClient->_need_quit)
        {
            break;
        }
        
        request = NULL;
        
        pthread_mutex_lock(&httpClient->_requestQueueMutex);
        if (httpClient->_requestQueue.count() > 0)
        {
            request = (CCHttpRequest *)httpClient->_requestQueue.objectAtIndex(0);
            httpClient->_requestQueue.removeObjectAtIndex(0);
        }
        pthread_mutex_unlock(&httpClient->_requestQueueMutex);
        
        if (NULL == request)
        {
        	pthread_cond_wait(&httpClient->_sleepCondition, &httpClient->_sleepMutex);
#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
			Sleep(100);
#else
			usleep(100000);
#endif
            continue;
        }
        
       
        CCHttpResponse *response = new CCHttpResponse(request);
         request->release();
        
        long responseCode = -1;
        int retValue = 0;

        switch (request->getRequestType())
        {
            case CCHttpRequest::kHttpGet: // HTTP GET
                retValue = processGetTask(request,
                                          writeData, 
                                          response->getResponseData(), 
                                          &responseCode,
                                          writeHeaderData,
                                          response->getResponseHeader());
                break;
            
            case CCHttpRequest::kHttpPost: // HTTP POST
                retValue = processPostTask(request,
                                           writeData, 
                                           response->getResponseData(), 
                                           &responseCode,
                                           writeHeaderData,
                                           response->getResponseHeader());
                break;

            case CCHttpRequest::kHttpPut:
                retValue = processPutTask(request,
                                          writeData,
                                          response->getResponseData(),
                                          &responseCode,
                                          writeHeaderData,
                                          response->getResponseHeader());
                break;

            case CCHttpRequest::kHttpDelete:
                retValue = processDeleteTask(request,
                                             writeData,
                                             response->getResponseData(),
                                             &responseCode,
                                             writeHeaderData,
                                             response->getResponseHeader());
                break;
            
            default:
                CCAssert(true, "CCHttpClient: unkown request type, only GET and POSt are supported");
                break;
        }
                
        // write data to HttpResponse
        response->setResponseCode(responseCode);
        if (retValue != 0)
        {
            response->setSucceed(false);
            response->setErrorBuffer(httpClient->_errorBuffer);
        }
        else
        {
            response->setSucceed(true);
        }

        
        pthread_mutex_lock(&httpClient->_responseQueueMutex);
        httpClient->_responseQueue.addObject(response);
        pthread_mutex_unlock(&httpClient->_responseQueueMutex);
        
        CCDirector::sharedDirector()->getScheduler()->resumeTarget(httpClient);
    }
    
    pthread_mutex_lock(&httpClient->_requestQueueMutex);
	httpClient->_requestQueue.removeAllObjects();
    pthread_mutex_unlock(&httpClient->_requestQueueMutex);
    httpClient->_asyncRequestCount -= httpClient->_requestQueue.count();
    
    if (httpClient->_requestQueue.count() > 0)
    {
        
        pthread_mutex_destroy(&httpClient->_requestQueueMutex);
        pthread_mutex_destroy(&httpClient->_responseQueueMutex);
        
        pthread_mutex_destroy(&httpClient->_sleepMutex);
        pthread_cond_destroy(&httpClient->_sleepCondition);

        httpClient->_requestQueue.removeAllObjects();
        httpClient->_responseQueue.removeAllObjects();
    }

    pthread_exit(NULL);
    
    return 0;
}

//Configure curl's timeout property
static bool configureCURL(CURL *handle, CCHttpClient* httpClient)
{
    if (!handle) {
        return false;
    }
    
    int32_t code;
    code = curl_easy_setopt(handle, CURLOPT_ERRORBUFFER, httpClient->_errorBuffer);
    if (code != CURLE_OK) {
        return false;
    }
    code = curl_easy_setopt(handle, CURLOPT_TIMEOUT, CCHttpClient::getInstance()->getTimeoutForRead());
    if (code != CURLE_OK) {
        return false;
    }
    code = curl_easy_setopt(handle, CURLOPT_CONNECTTIMEOUT, CCHttpClient::getInstance()->getTimeoutForConnect());
    if (code != CURLE_OK) {
        return false;
    }
    if (httpClient->_sslCaFilename.empty())
    {
        curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0L);
        curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, 0L);
    }
    else
    {
        curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 1L);
        curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, 2L);
        curl_easy_setopt(handle, CURLOPT_CAINFO, httpClient->_sslCaFilename.c_str());
    }
    
    curl_easy_setopt(handle, CURLOPT_NOSIGNAL, 1L);

    return true;
}

class CURLRaii
{
    CURL *m_curl;
    
    curl_slist *m_headers;
    
public:
    CURLRaii()
        : m_curl(curl_easy_init())
        , m_headers(NULL)
    {
    }

    ~CURLRaii()
    {
        if (m_curl)
            curl_easy_cleanup(m_curl);

        if (m_headers)
            curl_slist_free_all(m_headers);
    }

    template <class T>
    bool setOption(CURLoption option, T data)
    {
        return CURLE_OK == curl_easy_setopt(m_curl, option, data);
    }

    /**
     * @brief Inits CURL instance for common usage
     * @param request Null not allowed
     * @param callback Response write callback
     * @param stream Response write stream
     */
    bool init(CCHttpRequest *request, write_callback callback, void *stream, write_callback headerCallback, void *headerStream)
    {
        if (!m_curl)
            return false;
        if (!configureCURL(m_curl, s_pHttpClient[request->getThreadID()]))
            return false;

        /* get custom header data (if set) */
       	std::vector<std::string> headers=request->getHeaders();
        if(!headers.empty())
        {
            /* append custom headers one by one */
            for (std::vector<std::string>::iterator it = headers.begin(); it != headers.end(); ++it)
                m_headers = curl_slist_append(m_headers,it->c_str());
            /* set custom headers for curl */
            if (!setOption(CURLOPT_HTTPHEADER, m_headers))
                return false;
        }

        return setOption(CURLOPT_URL, request->getUrl())
                && setOption(CURLOPT_WRITEFUNCTION, callback)
                && setOption(CURLOPT_WRITEDATA, stream)
                && setOption(CURLOPT_HEADERFUNCTION, headerCallback)
                && setOption(CURLOPT_HEADERDATA, headerStream);
        
    }

    bool perform(long *responseCode)
    {
        if (CURLE_OK != curl_easy_perform(m_curl))
            return false;
        CURLcode code = curl_easy_getinfo(m_curl, CURLINFO_RESPONSE_CODE, responseCode);
        if (code != CURLE_OK || *responseCode != 200)
            return false;
        
        return true;
    }
};

//Process Get Request
static int processGetTask(CCHttpRequest *request, write_callback callback, void *stream, long *responseCode, write_callback headerCallback, void *headerStream)
{
    CURLRaii curl;
    bool ok = curl.init(request, callback, stream, headerCallback, headerStream)
            && curl.setOption(CURLOPT_FOLLOWLOCATION, true)
            && curl.perform(responseCode);
    return ok ? 0 : 1;
}

//Process POST Request
static int processPostTask(CCHttpRequest *request, write_callback callback, void *stream, long *responseCode, write_callback headerCallback, void *headerStream)
{
    CURLRaii curl;
    bool ok = curl.init(request, callback, stream, headerCallback, headerStream)
            && curl.setOption(CURLOPT_POST, 1)
            && curl.setOption(CURLOPT_POSTFIELDS, request->getRequestData())
            && curl.setOption(CURLOPT_POSTFIELDSIZE, request->getRequestDataSize())
            && curl.perform(responseCode);
    return ok ? 0 : 1;
}

//Process PUT Request
static int processPutTask(CCHttpRequest *request, write_callback callback, void *stream, long *responseCode, write_callback headerCallback, void *headerStream)
{
    CURLRaii curl;
    bool ok = curl.init(request, callback, stream, headerCallback, headerStream)
            && curl.setOption(CURLOPT_CUSTOMREQUEST, "PUT")
            && curl.setOption(CURLOPT_POSTFIELDS, request->getRequestData())
            && curl.setOption(CURLOPT_POSTFIELDSIZE, request->getRequestDataSize())
            && curl.perform(responseCode);
    return ok ? 0 : 1;
}

//Process DELETE Request
static int processDeleteTask(CCHttpRequest *request, write_callback callback, void *stream, long *responseCode, write_callback headerCallback, void *headerStream)
{
    CURLRaii curl;
    bool ok = curl.init(request, callback, stream, headerCallback, headerStream)
            && curl.setOption(CURLOPT_CUSTOMREQUEST, "DELETE")
            && curl.setOption(CURLOPT_FOLLOWLOCATION, true)
            && curl.perform(responseCode);
    return ok ? 0 : 1;
}

// HttpClient implementation
CCHttpClient* CCHttpClient::getInstance(int thread)
{
    if (thread >= MAX_Thread)
    {
        return NULL;
    }
    if (s_pHttpClient[thread] == NULL)
    {
        s_pHttpClient[thread] = new CCHttpClient(thread);
    }
    
    return s_pHttpClient[thread];

}

void CCHttpClient::destroyInstance(int thread)
{
    CCAssert(s_pHttpClient[thread], "");
    CCDirector::sharedDirector()->getScheduler()->unscheduleSelector(schedule_selector(CCHttpClient::dispatchResponseCallbacks), s_pHttpClient[thread]);
    s_pHttpClient[thread]->release();
}
unsigned CCHttpClient::GetResDownSize(std::string url)
{
	for (unsigned u = 0; u < MAX_Thread; u++)
	{
		CCHttpClient* httpClient = s_pHttpClient[u];
		if (httpClient != NULL)
		{
			pthread_mutex_lock(&httpClient->_responseQueueMutex);
			CCObject* pObject = NULL;
			CCARRAY_FOREACH(&httpClient->_responseQueue, pObject)
			{
				CCHttpResponse* pRes = (CCHttpResponse*)pObject;
				if (pRes->getHttpRequest()->getUrl() == url)
				{
					pthread_mutex_unlock(&httpClient->_responseQueueMutex);
					return pRes->getResponseData()->size();
				}
			}
			pthread_mutex_unlock(&httpClient->_responseQueueMutex);
		}
	}

	return 0;
}

CCHttpClient::CCHttpClient(int thread)
: _timeoutForConnect(30)
, _timeoutForRead(60)
, _threadID(thread)
, _asyncRequestCount(0)
, _need_quit(false)
, _networkThread(pthread_t())
, _requestQueueMutex(pthread_mutex_t())
, _responseQueueMutex(pthread_mutex_t())
, _sleepMutex(pthread_mutex_t())
, _sleepCondition(pthread_cond_t())
{
    CCDirector::sharedDirector()->getScheduler()->scheduleSelector(
                    schedule_selector(CCHttpClient::dispatchResponseCallbacks), this, 0, false);
    CCDirector::sharedDirector()->getScheduler()->pauseTarget(this);

    lazyInitThreadSemphore();
}

CCHttpClient::~CCHttpClient()
{
    _need_quit = true;
    
    if (_requestQueue.count() > 0)
    {
        pthread_cond_signal(&_sleepCondition);
    }
    
    s_pHttpClient[_threadID] = NULL;
}

//Lazy create semaphore & mutex & thread
bool CCHttpClient::lazyInitThreadSemphore()
{
    if (_requestQueue.count() > 0)
    {
        return true;
    }
    else
    {
        pthread_mutex_init(&_requestQueueMutex, NULL);
        pthread_mutex_init(&_responseQueueMutex, NULL);
        
        pthread_mutex_init(&_sleepMutex, NULL);
        pthread_cond_init(&_sleepCondition, NULL);

        pthread_create(&_networkThread, NULL, networkThread, this);
        pthread_detach(_networkThread);
        
        _need_quit = false;
    }
    
    return true;
}

//Add a get task to queue
void CCHttpClient::send(CCHttpRequest* request)
{    
    if (!request)
    {
        return;
    }
        
    ++_asyncRequestCount;
    
	request->setThreadID(_threadID);
    request->retain();
        
    pthread_mutex_lock(&_requestQueueMutex);
    _requestQueue.addObject(request);
    pthread_mutex_unlock(&_requestQueueMutex);
    
    pthread_cond_signal(&_sleepCondition);
}

// Poll and notify main thread if responses exists in queue
void CCHttpClient::dispatchResponseCallbacks(float delta)
{
    // CCLog("CCHttpClient::dispatchResponseCallbacks is running");
    
    CCHttpResponse* response = NULL;
    
    pthread_mutex_lock(&_responseQueueMutex);
    if (_responseQueue.count() > 0)
    {
        response = (CCHttpResponse*)_responseQueue.objectAtIndex(0);
        _responseQueue.removeObjectAtIndex(0);
    }
    pthread_mutex_unlock(&_responseQueueMutex);
    
    if (response)
    {
        --_asyncRequestCount;
        
        CCHttpRequest *request = response->getHttpRequest();
        if(request == NULL)
			return;
        CCObject *pTarget = request->getTarget();
        SEL_HttpResponse pSelector = request->getSelector();

        if (pTarget && pSelector) 
        {
            (pTarget->*pSelector)(this, response);
        }
        
        response->release();
    }
    
    if (0 == _asyncRequestCount) 
    {
        CCDirector::sharedDirector()->getScheduler()->pauseTarget(this);
    }
    
}

NS_CC_EXT_END




